<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>体检记录</h2>
          <el-form :inline="true" :model="searchForm" ref="searchFormRef">
            <el-form-item label="体检时间" prop="dateRange">
              <div style="display: flex; gap: 10px;">
                <el-date-picker
                    v-model="searchForm.startTime"
                    type="date"
                    placeholder="开始日期"
                    value-format="YYYY-MM-DD"
                    :max-date="searchForm.endTime"
                />
                <span style="align-self: center">至</span>
                <el-date-picker
                    v-model="searchForm.endTime"
                    type="date"
                    placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    :min-date="searchForm.startTime"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
              <el-button
                  type="primary"
                  icon="el-icon-plus"
                  @click="showFormDialog = true"
              >
                新增体检记录
              </el-button>
            </el-form-item>
          </el-form>


        </div>
      </template>
      
      <!-- 体检记录表格 -->
      <el-table :data="recordList" border stripe v-loading="loading" element-loading-text="数据加载中..." element-loading-background="rgba(255, 255, 255, 0.8)">

        <el-table-column prop="checkupDate" label="体检日期" width="180" align="center"></el-table-column>
        <el-table-column prop="elderName" label="老人" width="120" align="center"></el-table-column>

        <el-table-column
            prop="height"
            label="身高(cm)"
            width="100"
            align="center"
        >
          <template #default="{row}">
            {{ row.height || '-' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="weight"
            label="体重(kg)"
            width="100"
            align="center"
        >
          <template #default="{row}">
            {{ row.weight || '-' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="bloodPressure"
            label="血压(mmHg)"
            width="130"
            align="center"
        >
          <template #default="{row}">
            <el-tag v-if="row.bloodPressure" type="info">
              {{ row.bloodPressure }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="heartRate"
            label="心率(bpm)"
            width="110"
            align="center"
        >
          <template #default="{row}">
            <div :class="{'warning-text': row.heartRate > 100}">
              {{ row.heartRate || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="bloodSugar"
            label="血糖(mmol/L)"
            width="130"
            align="center"
        >
          <template #default="{row}">
            <div :class="{
              'warning-text': row.bloodSugar > 6.1 || row.bloodSugar < 3.9
            }">
              {{ row.bloodSugar !== null && row.bloodSugar !== undefined ? row.bloodSugar.toFixed(1) : '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="liverFunction"
            label="肝功能"
            width="100"
            align="center"
        >
          <template #default="{row}">
            <el-tag :type="row.liverFunction === '异常' ? 'danger' : 'success'">
              {{ row.liverFunction || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="doctorComment"
            label="医生总评"
            min-width="180"
        >
          <template #default="{row}">
            <div style="white-space: pre-wrap;">{{ row.doctorComment || '暂无总评' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{row}">
            <el-button type="primary" link @click="showDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px">
        <el-pagination
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :page-size="pageInfo.pageSize"
            :current-page="pageInfo.pageNum"
            :total="pageInfo.total"
        ></el-pagination>
      </div>

      <el-drawer
          v-model="detailVisible"
          title="体检详情"
          size="50%"
      >
        <div class="drawer-content">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="体检日期">
              {{ currentDetail.checkupDate ? dayjs(currentDetail.checkupDate).format('YYYY-MM-DD') : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="记录护工">
              {{ currentDetail.staffName || '未知' }}
            </el-descriptions-item>
          </el-descriptions>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">基础体征</div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="detail-item">
                  <label>身高：</label>
                  <span>{{ currentDetail.height || '-' }} cm</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>体重：</label>
                  <span>{{ currentDetail.weight || '-' }} kg</span>
                </div>
              </el-col>

              <el-col :span="8">
                <div class="detail-item">
                  <label>血压：</label>
                  <span>{{ currentDetail.bloodPressure || '-' }} mmHg</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>心率：</label>
                  <span>{{ currentDetail.heartRate || '-' }} bpm</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">血液检查</div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="detail-item">
                  <label>血糖：</label>
                  <span>{{ currentDetail.bloodSugar !== null && currentDetail.bloodSugar !== undefined ? currentDetail.bloodSugar.toFixed(1) : '-' }} mmol/L</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>胆固醇：</label>
                  <span>{{ currentDetail.cholesterol || '-' }} mmol/L</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>甘油三酯：</label>
                  <span>{{ currentDetail.triglyceride || '-' }} mmol/L</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>血红蛋白：</label>
                  <span>{{ currentDetail.hemoglobin || '-' }} g/L</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">器官功能</div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="detail-item">
                  <label>肝功能：</label>
                  <el-tag :type="currentDetail.liverFunction === '异常' ? 'danger' : 'success'">
                    {{ currentDetail.liverFunction || '-' }}
                  </el-tag>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>肾功能：</label>
                  <el-tag :type="currentDetail.renalFunction === '异常' ? 'danger' : 'success'">
                    {{ currentDetail.renalFunction || '-' }}
                  </el-tag>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>心电图：</label>
                  <span>{{ currentDetail.ecgResult || '无记录' }}</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">其他检查</div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="detail-item">
                  <label>胸片结果：</label>
                  <span>{{ currentDetail.chestXray || '无异常' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>B超结果：</label>
                  <span>{{ currentDetail.ultrasound || '无异常' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>视力（左）：</label>
                  <span>{{ currentDetail.visionLeft || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>视力（右）：</label>
                  <span>{{ currentDetail.visionRight || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <label>听力测试：</label>
                  <span>{{ currentDetail.hearingTest || '正常' }}</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">医生建议</div>
            </template>
            <div class="detail-item">
              <div style="white-space: pre-wrap; line-height: 1.6;">
                {{ currentDetail.doctorComment || '暂无医生建议' }}
              </div>
            </div>
            <div class="detail-item" v-if="currentDetail.recommendation">
              <label>健康建议：</label>
              <span style="color: #67C23A;">{{ currentDetail.recommendation }}</span>
            </div>
          </el-card>
        </div>
      </el-drawer>

      <!-- 新增记录弹窗 -->
      <el-dialog
          title="新增体检记录"
          v-model="showFormDialog"
          width="800px"
          @closed="resetForm"
      >
        <el-form
            :model="form"
            label-width="120px"
            :rules="rules"
            ref="formRef"
        >
          <el-form-item label="老人姓名" prop="elderId">
            <el-select
                v-model="form.elderId"
                placeholder="请选择老人"
                style="width: 100%"
            >
              <el-option
                  v-for="elder in elderList"
                  :key="elder.id"
                  :label="elder.nickname"
                  :value="elder.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="体检日期" prop="checkupDate">
            <el-date-picker
                v-model="form.checkupDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">
                <span>基础体征</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="身高(cm)" prop="height">
                  <el-input-number
                      v-model="form.height"
                      :min="100"
                      :max="250"
                      :step="1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="体重(kg)" prop="weight">
                  <el-input-number
                      v-model="form.weight"
                      :min="30"
                      :max="200"
                      :step="1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="血压(mmHg)" prop="bloodPressure">
                  <el-input
                      v-model="form.bloodPressure"
                      placeholder="如：120/80"
                      style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">
                <span>生命体征</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="心率(bpm)" prop="heartRate">
                  <el-input-number
                      v-model="form.heartRate"
                      :min="30"
                      :max="200"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="血糖(mmol/L)" prop="bloodSugar">
                  <el-input-number
                      v-model="form.bloodSugar"
                      :min="2"
                      :max="30"
                      :step="0.1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="肝功能" prop="liverFunction">
                  <el-select
                      v-model="form.liverFunction"
                      placeholder="请选择"
                      style="width: 100%"
                  >
                    <el-option label="正常" value="正常"></el-option>
                    <el-option label="异常" value="异常"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">
                <span>生化指标</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="总胆固醇(mmol/L)" prop="cholesterol">
                  <el-input-number
                      v-model="form.cholesterol"
                      :min="2"
                      :max="10"
                      :step="0.1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="甘油三酯(mmol/L)" prop="triglyceride">
                  <el-input-number
                      v-model="form.triglyceride"
                      :min="0.5"
                      :max="5"
                      :step="0.1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="血红蛋白(g/L)" prop="hemoglobin">
                  <el-input-number
                      v-model="form.hemoglobin"
                      :min="50"
                      :max="200"
                      :step="1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">
                <span>检查结果</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="肾功能" prop="renalFunction">
                  <el-select
                      v-model="form.renalFunction"
                      placeholder="请选择"
                      style="width: 100%"
                  >
                    <el-option label="正常" value="正常"></el-option>
                    <el-option label="异常" value="异常"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="心电图" prop="ecgResult">
                  <el-input
                      v-model="form.ecgResult"
                      placeholder="请输入结果"
                      style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="胸片结果" prop="chestXray">
                  <el-input
                      v-model="form.chestXray"
                      placeholder="请输入结果"
                      style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="B超结果" prop="ultrasound">
                  <el-input
                      v-model="form.ultrasound"
                      placeholder="请输入结果"
                      style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="左眼视力" prop="visionLeft">
                  <el-input-number
                      v-model="form.visionLeft"
                      :min="0"
                      :max="5"
                      :step="0.1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="右眼视力" prop="visionRight">
                  <el-input-number
                      v-model="form.visionRight"
                      :min="0"
                      :max="5"
                      :step="0.1"
                      style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="听力测试" prop="hearingTest">
              <el-input
                  v-model="form.hearingTest"
                  placeholder="请输入结果"
                  style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-card>

          <el-card class="section-card">
            <template #header>
              <div class="card-sub-header">
                <span>健康评估</span>
              </div>
            </template>
            <el-form-item label="医生总评" prop="doctorComment" required>
              <el-input
                  type="textarea"
                  v-model="form.doctorComment"
                  :rows="4"
                  placeholder="请输入综合评估意见"
                  style="width: 100%"
              ></el-input>
            </el-form-item>
            <el-form-item label="健康建议" prop="recommendation" required>
              <el-input
                  type="textarea"
                  v-model="form.recommendation"
                  :rows="3"
                  placeholder="请输入健康建议"
                  style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-card>

          <el-form-item style="margin-top: 20px">
            <el-button type="primary" @click="submit">提交记录</el-button>
            <el-button @click="showFormDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/utils/http.js'
import utils from "@/utils/tools.js";
import dayjs from 'dayjs'

const showFormDialog = ref(false)
const recordList = ref([])
const elderList = ref([])
const searchForm = reactive({
  startTime: '',
  endTime: ''
})

const searchFormRef = ref()
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const form = ref({
  elderId: '',
  checkupDate: '',
  height: null,
  weight: null,
  bloodPressure: '',
  heartRate: null,
  bloodSugar: null,
  liverFunction: '',
  cholesterol: null,
  triglyceride: null,
  hemoglobin: null,
  renalFunction: '',
  ecgResult: '',
  chestXray: '',
  ultrasound: '',
  visionLeft: null,
  visionRight: null,
  hearingTest: '',
  doctorComment: '',
  recommendation: ''
})

const loading = ref(false)
const formRef = ref(null)
const detailVisible = ref(false)
const currentDetail = ref({})

onMounted(async () => {
  await getElderList()
  await getCheckupRecords()
})

function search() {
  pageInfo.value.pageNum = 1
  getCheckupRecords()
}

function resetSearch() {
  searchFormRef.value.resetFields()
  searchForm.startTime = ''
  searchForm.endTime = ''
  getCheckupRecords()
}

async function getElderList() {
  try {
    const staff = await http.get(`/staff/selectById/${utils.getCurrentUser().id}`)
    if (staff.data) {
      const buildingId = staff.data.buildingId
      const res = await http.get(`/elder/selectByBuildingId/${buildingId}`)
      elderList.value = res.data
    }
  } catch (e) {
    if (e.response?.status !== 404) {
      ElMessage.error('获取老人列表失败')
    }
  }
}

async function getCheckupRecords() {
  loading.value = true
  try {
    const res = await http.get('/checkupRecord/page', {
      params: {
        staffId: utils.getCurrentUser().id,
        pageNum: pageInfo.value.pageNum,
        pageSize: pageInfo.value.pageSize,
        startTime: searchForm.startTime,
        endTime: searchForm.endTime
      }
    })
    recordList.value = res.data.list
    pageInfo.value.total = res.data.total
  } catch (e) {
    ElMessage.error('获取体检记录失败')
  } finally {
    loading.value = false
  }
}


const rules = {
  elderId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  checkupDate: [{ required: true, message: '请选择体检日期', trigger: 'change' }],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' },
    { type: 'number', min: 100, max: 250, message: '身高应在100-250cm之间' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' },
    { type: 'number', min: 30, max: 200, message: '体重应在30-200kg之间' }
  ],
  bloodPressure: [
    { required: true, message: '请输入血压值', trigger: 'blur' },
    { pattern: /^\d+\/\d+$/, message: '格式如：120/80' }
  ],
  heartRate: [
    { required: true, message: '请输入心率', trigger: 'blur' },
    { type: 'number', min: 30, max: 200, message: '心率应在30-200bpm之间' }
  ],
  bloodSugar: [
    { required: true, message: '请输入血糖值', trigger: 'blur' },
    { type: 'number', min: 2, max: 30, message: '血糖应在2-30mmol/L之间' }
  ],
  liverFunction: [
    { required: true, message: '请选择肝功能状态', trigger: 'change' }
  ],
  cholesterol: [
    { required: true, message: '请输入总胆固醇值', trigger: 'blur' },
    { type: 'number', min: 2, max: 10, message: '值应在2-10mmol/L之间' }
  ],
  triglyceride: [
    { required: true, message: '请输入甘油三酯值', trigger: 'blur' },
    { type: 'number', min: 0.5, max: 5, message: '值应在0.5-5mmol/L之间' }
  ],
  hemoglobin: [
    { required: true, message: '请输入血红蛋白值', trigger: 'blur' },
    { type: 'number', min: 50, max: 200, message: '值应在50-200g/L之间' }
  ],
  renalFunction: [
    { required: true, message: '请选择肾功能状态', trigger: 'change' }
  ],
  ecgResult: [
    { required: true, message: '请输入心电图结果', trigger: 'blur' }
  ],
  chestXray: [
    { required: true, message: '请输入胸片结果', trigger: 'blur' }
  ],
  ultrasound: [
    { required: true, message: '请输入B超结果', trigger: 'blur' }
  ],
  visionLeft: [
    { required: true, message: '请输入左眼视力', trigger: 'blur' },
    { type: 'number', min: 0, max: 5, message: '视力值应在0-5之间' }
  ],
  visionRight: [
    { required: true, message: '请输入右眼视力', trigger: 'blur' },
    { type: 'number', min: 0, max: 5, message: '视力值应在0-5之间' }
  ],
  hearingTest: [
    { required: true, message: '请输入听力测试结果', trigger: 'blur' }
  ],
  recommendation: [
    { required: true, message: '请输入健康建议', trigger: 'blur' }
  ],
  doctorComment: [
    { required: true, message: '请输入医生总评', trigger: 'blur' }
  ]
}

const submit = () => {
  formRef.value.validate(valid => {
    if (!valid) return
    
    http.post('/checkupRecord/add', {
      ...form.value,
      staffId: utils.getCurrentUser().id
    }).then(() => {
      ElMessage.success('记录提交成功')
      getCheckupRecords()
      showFormDialog.value = false
      resetForm()
    }).catch(e => {
      console.error('完整错误信息:', e.response)
      ElMessage.error(e.response?.data?.message || '提交失败')
    })
  })
}

const showDetail = (row) => {
  currentDetail.value = row
  detailVisible.value = true
}

const handleSizeChange = (val) => {
  pageInfo.value.pageSize = val
  getCheckupRecords()
}

const handleCurrentChange = (val) => {
  pageInfo.value.pageNum = val
  getCheckupRecords()
}

const resetForm = () => {
  form.value = {
    elderId: '',
    checkupDate: '',
    height: null,
    weight: null,
    bloodPressure: '',
    heartRate: null,
    bloodSugar: null,
    liverFunction: '',
    cholesterol: null,
    triglyceride: null,
    hemoglobin: null,
    renalFunction: '',
    ecgResult: '',
    chestXray: '',
    ultrasound: '',
    visionLeft: null,
    visionRight: null,
    hearingTest: '',
    doctorComment: '',
    recommendation: ''
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.report-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #666;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

.drawer-content {
  padding: 20px;
}

.section-card {
  margin-top: 20px;
}

.detail-item {
  margin-bottom: 15px;
  font-size: 14px;
}
.detail-item label {
  color: #909399;
  margin-right: 10px;
}
</style> 